﻿using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using ColladaDotNet;


namespace contentviewer.ViewModel
{
    public class NodeViewModel : ViewModelBase
    {
        #region Data

        static readonly NodeViewModel DummyChild = new NodeViewModel();

        readonly ObservableCollection<NodeViewModel> _children;
        readonly NodeViewModel _parent;
        readonly NodeViewModel _root;

        bool _isExpanded;
        bool _isSelected;

        #endregion

        #region Constructors

        protected NodeViewModel(NodeViewModel root, NodeViewModel parent)
        {
            _root = root;
            _parent = parent;

            _children = new ObservableCollection<NodeViewModel>();
            _children.Add(DummyChild);
        }

        private NodeViewModel()
        {
        }
        #endregion

        public ObservableCollection<NodeViewModel> Children
        {
            get { return _children; }
        }

        public bool HasDummyChild
        {
            get { return this.Children.Count == 1 && this.Children[0] == DummyChild; }
        }

        public bool IsExpanded
        {
            get { return _isExpanded; }
            set
            {
                if (value != _isExpanded)
                {
                    _isExpanded = value;
                    RaisePropertyChanged("IsExpanded");
                }

                if (_isExpanded && _parent != null)
                    _parent.IsExpanded = true;

                if (this.HasDummyChild)
                {
                    this.LoadChildren();
                }
            }
        }

        public virtual bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                if (value != _isSelected)
                {
                    _isSelected = value;
                    RaisePropertyChanged("IsSelected");
                }
            }
        }

        protected virtual void LoadChildren()
        {
            if (HasDummyChild)
                _children.Remove(DummyChild);
        }

        public NodeViewModel Parent
        {
            get { return _parent; }
        }

        public NodeViewModel Root
        {
            get { return _root; }
        }
    }
}
